﻿module Sustainalytics.CompanyOverview {

    export class CompanyOverviewController {

        // current company

        public companyNameQueryString: string;
        public company: Company.CorporateDataExtendedDto;
        private $routeParams: any;

        public hasGccsClaim: boolean;
        public hasPiClaim: boolean;
        public hasGovernanceClaim: boolean;
        public hasEsgClaim: boolean;
        public hasRiskClaim: boolean;
        public hasControvercyClaim: boolean;

        public hasEsgResearchAvailable: boolean;
        public hasEsgRiskResearchAvailable: boolean;
        public hasControversyResearchAvailable: boolean;
        public hasGccsResearchAvailable: boolean;
        public hasGovernanceResearchAvailable: boolean;
        public hasProductInvolvementResearchAvailable: boolean;

        public hasEsgResearchInProgress: boolean;
        public hasEsgRiskResearchInProgress: boolean;
        public hasControversyResearchInProgress: boolean;
        public hasGccsResearchInProgress: boolean;
        public hasGovernanceResearchInProgress: boolean;
        public hasProductInvolvementResearchInProgress: boolean;

        public esgResearchTypeText: string;
        public esgOverallPerformanceScoreValue: number;
        public esgOverallPerformanceScoreText: string;
        public esgOverallPerformancePercentileValue: string;
        public esgOverallPerformancePercentileText: string;
        public controversyHighestLevelValue: number;
        public controversyHighestLevelText: string;
        public gcOverallAssessment: GCCS.GCAssessment;

        public newsArticles: NewsArticleDto[] = [];
        public allNewsArticles: NewsArticleDto[] = null;
        public newsArticlesTake: number = 0;
        public maxNewsArticlesTake: number = 5;
        public foundNewsArticles: boolean = false;

        constructor(
            public $scope: ng.IScope,
            public $rootScope: ng.IScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private companyOverviewService: ICompanyOverviewService, 
            private numberUtilityService: Common.NumberUtilityService, 
            private gcOverallCompanySummaryService: GCCS.IGCOverallCompanySummaryService,
            private RoutingService: Routing.IRoutingService,
            private CompanyService: Company.ICompanyService,
            //private esgOverallPerformanceSummaryService: EsgRatings.IEsgOverallPerformanceSummaryService,
            private $modal: Common.IModal) {

            var ctx = this;
            $scope['companyOverview'] = ctx;
            ctx.$routeParams = ctx.RoutingService.getRouteParams();

            //GCCS
            var gcRouteSecurity = new Routing.RouteSecurity().addService('GCRouteSecurityService');
            var gcPromise = ctx.RoutingService.validateRouteSecurity(gcRouteSecurity);
            gcPromise.then(val => {
                this.hasGccsClaim = val;
            });

            //PIResearch
            var piRouteSecurity = new Routing.RouteSecurity().addService('PICompanyRouteSecurityService');
            var piPromise = ctx.RoutingService.validateRouteSecurity(piRouteSecurity);
            piPromise.then(val => {
                this.hasPiClaim = val;
            });

            //governance
            var govRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/governance', parameters: [] });
            var govPromise = ctx.RoutingService.validateRouteSecurity(govRouteSecurity);
            govPromise.then(val => {
                this.hasGovernanceClaim = val;
            });

            //esg research
            var esgRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/esgratings/{companyId}', parameters: [] });
            var esgPromise = ctx.RoutingService.validateRouteSecurity(esgRouteSecurity);
            esgPromise.then(val => {
                this.hasEsgClaim = val;
            });

            //risk rating research
            var riskRatingRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/riskratings/{companyId}', parameters: [] });
            var riskRatingPromise = ctx.RoutingService.validateRouteSecurity(riskRatingRouteSecurity);
            riskRatingPromise.then(val => {
                this.hasRiskClaim = val;
            });

            //controvercy
            var controvercyRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'GET', resource: 'api/v1/company/{companyId}/esgControversyIndicator', parameters: [] });
            var controvercyPromise = ctx.RoutingService.validateRouteSecurity(controvercyRouteSecurity);
            controvercyPromise.then(val => {
                this.hasControvercyClaim = val;
            });

            ctx.newsArticlesTake = 0;
            ctx.foundNewsArticles = false;

            ctx.init();
        }

        private getEsgPositionText(esgPosition: EsgPositionEnum): string {

            switch (esgPosition) {
                case EsgPositionEnum.IndustryLeader:
                    return "Leader";
                case EsgPositionEnum.Outperformer:
                    return "Outperformer";
                case EsgPositionEnum.AveragePerformer:
                    return "Average Performer";
                case EsgPositionEnum.UnderPerformer:
                    return "Underperformer";
                case EsgPositionEnum.IndustryLaggard:
                    return "Laggard";
                default:
                    return null;
            }
        }

        // init controller data
        private init(): ng.IPromise<any> {
            var ctx = this;

            // get company name from route params
            var companyName: string = ctx.$routeParams['companyName'];
            ctx.companyNameQueryString = companyName;

            // get company by name
            var companyPromise = ctx.CompanyService.getByNameUrlFriendly(companyName, true);

            var def = ctx.$q.defer();

            companyPromise
                .success(company => {
                    this.company = company;
                    console.log(company);

                    ctx.setResearchStates(company);

                    if (ctx.$rootScope['userInfo'] == null) {
                        ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
                    }
                    var esgProfileId = ctx.$rootScope['userInfo'].esgProfileId;

                    var esgOverallPerformancePromise = this.companyOverviewService.getEsgOverallPerformance(company.id, esgProfileId);

                    var getNewsArticlesPromise = ctx.companyOverviewService.getNewsArticles(company.id);
                    getNewsArticlesPromise.then(function (res) {
                        ctx.$timeout(function () {
                            ctx.$scope.$apply(function () {
                                // set news articles
                                ctx.allNewsArticles = res;

                                ctx.foundNewsArticles = true;
                                if (ctx.allNewsArticles.length === 0) {
                                    ctx.foundNewsArticles = false;
                                        }

                                ctx.takeNewsArticles();
                            });
                        });
                    }, (reason) => {
                        ctx.foundNewsArticles = false;
                    });


                    esgOverallPerformancePromise.then(esgOverallPerformance => {
                        if (esgOverallPerformance) {
                            this.esgOverallPerformanceScoreValue = esgOverallPerformance.overall.score;
                            this.esgOverallPerformanceScoreText = esgOverallPerformance.overall.esgPosition.name;
                            this.esgOverallPerformancePercentileValue = esgOverallPerformance.percentile.comparativeGroupPercentileRank +
                                this.numberUtilityService.getOrdinalNameEnd(esgOverallPerformance.percentile.comparativeGroupPercentileRank);
                            this.esgOverallPerformancePercentileText = esgOverallPerformance.percentile.esgPosition.name;
                        }
                    }, err => def.reject(err));

                    var controversyQualitativePerformancePromise = this.companyOverviewService.getControversyQualitativePerformance(company.id);

                    controversyQualitativePerformancePromise.then(controversyIndicators => {
                        var maxAnswerCategory = -1, maxEventSeverity = "";
                        controversyIndicators.forEach(ci => {
                            if (ci.answerCategory > maxAnswerCategory) {
                                maxAnswerCategory = ci.answerCategory;
                                maxEventSeverity = ci.eventSeverity;
                            }
                        });

                        this.controversyHighestLevelValue = -1;
                        if (maxAnswerCategory != -1) {
                            this.controversyHighestLevelValue = maxAnswerCategory;
                            this.controversyHighestLevelText = maxEventSeverity;
                        }
                    }, err => def.reject(err));

                    var esgResearchTypePromise = ctx.companyOverviewService.getEsgResearchType(company.id);

                    esgResearchTypePromise.then(esgResearchType => {
                        this.esgResearchTypeText = esgResearchType;
                    }, err => def.reject(err));

                    var gcOverallAssessmentPromise = ctx.gcOverallCompanySummaryService.GetByCompany(company.id);

                    gcOverallAssessmentPromise.then(gcOverallCompanySummary => {
                        ctx.gcOverallAssessment = gcOverallCompanySummary.overallCompanyAssessment;
                    }, err => def.reject(err));

                    ctx.$q.all([esgOverallPerformancePromise, esgResearchTypePromise, controversyQualitativePerformancePromise, gcOverallAssessmentPromise])
                        .then(() => def.resolve(), err => def.reject(err));
                })
                .error(err => def.reject(err));

            return def.promise;
        }

        public takeNewsArticles = function () {
            var ctx = this;

            if (!ctx.allNewsArticles || ctx.allNewsArticles.length <= 0) {
                return;
            }

            var take = 0;

            for (var i = ctx.newsArticlesTake; i < ctx.allNewsArticles.length; i++) {
                ctx.newsArticles.push(ctx.allNewsArticles[i]);
                take++;

                if (take >= ctx.maxNewsArticlesTake) {
                    break;
                }
            }

            ctx.newsArticlesTake += take;

            if (ctx.newsArticlesTake >= ctx.allNewsArticles.length) {
                ctx.foundNewsArticles = false;
            }
        }


        public setResearchStates(company): void {
  
            this.hasEsgResearchAvailable = false;
            this.hasEsgResearchInProgress = false;

            this.hasGovernanceResearchAvailable = false;
            this.hasGovernanceResearchInProgress = false;

            this.hasControversyResearchAvailable = false;
            this.hasControversyResearchInProgress = false;

            this.hasGccsResearchAvailable = false;
            this.hasGccsResearchInProgress = false;

            this.hasProductInvolvementResearchAvailable = false;
            this.hasProductInvolvementResearchInProgress = false;

            if (company.comprehensiveEsgResearchState === 2) {
                this.hasEsgResearchAvailable = true;
            } else {
                if (company.coreEsgResearchState === 2) {
                    this.hasEsgResearchAvailable = true;
                } else {
                    if (company.comprehensiveEsgResearchState === 1 ||
                        company.coreEsgResearchState === 1) {
                        this.hasEsgResearchInProgress = true;
                    }
                }
            }

            if (company.corporateGovernanceResearchState === 2) {
                this.hasGovernanceResearchAvailable = true;
            } else {
                if (company.corporateGovernanceResearchState === 1) {
                    this.hasGovernanceResearchInProgress = true;
                }
            }

            if (company.controversyResearchState === 2) {
                this.hasControversyResearchAvailable = true;
            } else {
                if (company.controversyResearchState === 1) {
                    this.hasControversyResearchInProgress = true;
                }
            }

            if (company.gccsResearchState === 2) {
                this.hasGccsResearchAvailable = true;
            } else {
                if (company.gccsResearchState === 1) {
                    this.hasGccsResearchInProgress = true;
                }
            }

            if (company.productInvolvementResearchState === 2) {
                this.hasProductInvolvementResearchAvailable = true;
            } else {
                if (company.productInvolvementResearchState === 1) {
                    this.hasProductInvolvementResearchInProgress = true;
                }
            }

            if (company.riskRatingResearchState === 2) {
                this.hasEsgRiskResearchAvailable = true;
            } else {
                if (company.riskRatingResearchState === 1) {
                    this.hasEsgRiskResearchInProgress = true;
                }
            }
        }


        public openSavePortfolio = function () {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: '/Views/Research/Common/savePortfolio_dialog.tpl.html',
                    controller: 'CompanyAddToPortfolioController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        companyId: () => {

                            return ctx.company.isCoverageEntity ? ctx.company.coverageId : ctx.company.id;
                        },
                        companyText: function () {
                            var companyText = ctx.company.companyName;
                            if (ctx.company.exchangeCode != null && ctx.company.ticker != null)
                                companyText += " (" + ctx.company.exchangeCode + ":" + ctx.company.ticker + ")";
                            return companyText;
                        }
                    }
                });

            modalInstance.result.then((item) => {
                //$scope.currentFilter.name = item.name;
                //$scope.currentFilter.shared = item.shared;
                //setIsModified(false);
            });
        };
    }    


    angular.module('Sustainalytics.CompanyOverview').controller('CompanyOverviewController',
        ['$scope', '$rootScope', '$q', '$timeout', 'CompanyOverviewService', 'NumberUtilityService', 'GCOverallCompanySummaryService', 'RoutingService', 'CompanyService', '$modal', CompanyOverviewController]);
}